<template>
	<view>
		<qf-image-cropper ref="qfImageCropperRef" :width="500" :height="500" :radius="30"
			@crop="handleCrop"></qf-image-cropper>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';

	// 创建一个引用
	const qfImageCropperRef = ref(null);

	// 在组件挂载后执行操作
	onMounted(() => {
		if (qfImageCropperRef.value) {
			qfImageCropperRef.value.chooseImage({
				sourceType: ['album']
			});
		}
	});

	function handleCrop(e) {
		// 调用上传文件的方法
		uploadImageToServer(e.tempFilePath);
		uni.previewImage({
			urls: [e.tempFilePath],
			current: 0
		});

	}

	function uploadImageToServer(tempFilePath) {
		const token = {
			"token": uni.getStorageSync("token")
		}
		const uploadTask = uni.uploadFile({
			url: 'http://localhost:9090/uniApp/articleApi/avatar', // 服务器上传接口地址
			filePath: tempFilePath,
			header: token,
			name: 'avatarfile', // 上传文件的字段名，服务器端需要根据这个字段名来接收文件
			success: (res) => {
				const data = JSON.parse(res.data)

				if (data.code === 200) {
					
					const userInfo = uni.getStorageSync("userInfo")
					userInfo.avatar = data.imgUrl
					uni.setStorageSync("userInfo", userInfo)

					uni.switchTab({
						url: "/pages/user/user",
						success: () => {
							console.log('页面跳转成功');
						},
						fail: (err) => {
							console.log('页面跳转失败', err);
						}
					})

				} else {
					uni.showToast({
						title: "上传失败",
						icon: "none"
					})

				}
			},
			fail: (err) => {
				console.log('上传失败', err);
			}
		});
	}
</script>

<style>

</style>